package com.zzq.controller.v1;


import com.zzq.config.K8sInit;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RequestMapping("/pod")
@RestController
@Slf4j
public class PodController {


    @Autowired
    private K8sInit k8sInit;


    /**
     * create pod
     * @return
     */
    @PostMapping("/createPod")
    public String test()  {
        String namespace = "default";
        try {
            HashMap<String, String> labels = new HashMap<String, String>();
            labels.put("app","nginx-pod-test");
            ApiClient client = k8sInit.getConnection();
            CoreV1Api apiInstance = new CoreV1Api(client);
            V1Pod createPod = new V1PodBuilder()
                    .withApiVersion("v1")
                    .withKind("Pod")
                    .withNewMetadata()
                    .withName("nginx-pod-test")
                    .withNamespace(namespace)
                    .withLabels(labels)
                    .endMetadata()
                    .withNewSpec()
                    .addNewContainer()
                    .withName("nginx-pod-test")
                    .withImage("nginx:1.14.2")
                    .withEnv()
                    .endContainer()
                    .endSpec()
                    .build();
            V1Pod createPodRes = apiInstance.createNamespacedPod(namespace, createPod, null, null, null);
            log.info("createPodRes:{}",createPodRes);
        } catch (ApiException e) {
            e.printStackTrace();
        }


        return "node test";
    }
}
